<template>
  <div ref="qrCodeDiv">
    <Card>
      <div style="display: flex; justify-content: space-between">
        <div></div>
        <div>
          <Form ref="searchForm" inline :label-width="70" class="search-form">
            <FormItem label="选择日期">
              <DatePicker
                clearable
                type="daterange"
                placement="bottom-end"
                placeholder="请选择日期"
                style="width: 200px"
                v-model="date"
                @on-change="changeDate"
              ></DatePicker>
            </FormItem>
            <FormItem style="margin-left: -35px" class="br">
              <Button
                :disabled="beyondTiem"
                @click="handleSearch"
                type="primary"
                >生成报告</Button
              >
              <Button :loading="loadingPDF" @click="handleReset"
                >导出PDF</Button
              >
            </FormItem>
          </Form>
        </div>
      </div>
      <Row>
        <Col span="9">
          <div class="company">
            <div class="companyimg">
              <img src="@/assets/customer.png" alt="" srcset="" />
            </div>
            <div class="companyinformation">
              <div style="font-weight: 600; margin-top: -5px">
                河南闪途科技有限公司
              </div>
              <div style="margin-top: 2px">联系电话：0391-5982286</div>
            </div>
          </div>
        </Col>
        <Col span="10" push="1">
          <div>
            <div class="Operation_analysis">运营分析报告</div>
            统计时间：{{ startime }}-{{ endtime }}
          </div>
        </Col>
        <Col span="5">
          <div class="tiems">报告时间：{{ currentTime }}</div>
        </Col>
      </Row>
      <div class="Lines"></div>
      <div style="margin: 20px 0"></div>
      <div style="margin-left: 10px; margin-right: 10px">
        <Row>
          <Table
            :loading="loading"
            border
            :columns="columns"
            :data="data"
            ref="table"
            class="table"
          ></Table>
        </Row>
        <div style="margin-top: 5px; font-size: 11px">
          环比统计区间： {{ ringRatioStart }}-{{ ringRatioEnd }}，{{
            ringRatioDay
          }}自然日；同比统计区间： {{ yearStart }}-{{ yearEnd }}，{{
            yearDay
          }}自然日
        </div>
      </div>
      <div class="QuantityStatistics">
        <OrderQuantityStatistics v-if="statistics" :timeSearch="timeSearch">
        </OrderQuantityStatistics>
      </div>
      <div class="timel">
        <el-timeline>
          <div>
            <el-timeline-item color="#008FFB" size="normal">
              <div class="timelineFont">发布</div>
              <div class="Goods">
                <SourceGoods
                  v-on:childSourceGoods="childSourceGoods"
                  v-if="statistics"
                  :timeSearch="timeSearch"
                >
                </SourceGoods>
                <div
                  style="margin-top: 55px; margin-left: 75px; font-size: 11px"
                >
                  本期共发布{{ goodsData.total_num }}票货源，其中定价{{
                    goodsData.price_num
                  }}票，竞价{{ goodsData.bidding_num }}票，定价货源成单量{{
                    goodsData.price_num
                  }}单，竞价货源成单量{{ goodsData.bidding_num }}单，总成单量{{
                    goodsData.total_num
                  }}单。
                </div>
              </div>
            </el-timeline-item>
            <el-timeline-item color="#3CB371" size="normal">
              <div class="timelineFont">调度</div>
              <div class="Ordercs">
                <Order
                  v-on:childOrder="childOrder"
                  v-if="statistics"
                  :timeSearch="timeSearch"
                >
                </Order>
                <div
                  style="margin-top: 55px; margin-left: 75px; font-size: 11px"
                >
                  本期共承运了{{
                    orderData.entrustedPieChart.carry_num
                  }}个订单，合同金额合计￥{{
                    this.carryTotal > 1 ? this.carryTotal.toFixed(2) : 0
                  }}， 委托了{{
                    orderData.entrustedPieChart.carry_num
                  }}个运单，合同金额合计￥
                  {{
                    this.entrustTotal > 1 ? this.entrustTotal.toFixed(2) : 0
                  }}。
                </div>
              </div>
            </el-timeline-item>
            <el-timeline-item color="#FF8C00" size="normal">
              <div class="timelineFont">运单</div>
              <div class="Ordercs">
                <Transport
                  v-if="statistics"
                  :timeSearch="timeSearch"
                  v-on:childTransport="childTransport"
                >
                </Transport>
                <div
                  style="margin-top: 55px; margin-left: 75px; font-size: 11px"
                >
                  本期共计运单量{{ waybillTotal }}单， 其中待执行{{
                    waybillData.orderPieChart.loading_num
                  }}单，在途{{
                    waybillData.orderPieChart.ontheway_num
                  }}单，业务及财务审核中{{
                    waybillData.orderPieChart.examine_num
                  }}单，已签收{{
                    waybillData.orderPieChart.signfor_num
                  }}单，总配载量{{
                    goodWeight > 1 ? goodWeight.toFixed(2) : 0
                  }}吨，总装载量{{
                    transGoodWeight > 1 ? transGoodWeight.toFixed(2) : 0
                  }}吨，总签收量{{
                    realGoodWeight > 1 ? realGoodWeight.toFixed(2) : 0
                  }}吨。
                </div>
              </div>
            </el-timeline-item>
          </div>
        </el-timeline>
      </div>
    </Card>
  </div>
</template>

<script>
// 根据你的实际请求api.js位置路径修改
import OrderQuantityStatistics from "./OrderQuantityStatistics.vue";
import SourceGoods from "./SourceGoods.vue";
import Order from "./order.vue";
import Transport from "./transport.vue";
import { getCompanyVoList } from "@/api/user";
import { operateRingRatio, operateTotal, operateEntrusted } from "@/api/index";
import html2canvas from "html2canvas";
import { el } from "date-fns/locale";
import { addDownloadRecord } from "@/api/index";
export default {
  name: "dataReporting",
  components: {
    OrderQuantityStatistics,
    SourceGoods,
    Order,
    Transport,
  },
  data() {
    return {
      // 环比时间
      ringRatioStart: "",
      ringRatioEnd: "",
      ringRatioDay: "",

      // 同比统计区间
      yearStart: "",
      yearEnd: "",
      yearDay: "",

      startList: "",
      endList: "",
      manyDays: "",
      loadingPDF: false,
      currentTime: "",
      startime: "",
      endtime: "",
      beyondTiem: false,
      // 货源
      goodsData: {},
      // 订单
      orderData: {
        entrustedPieChart: {},
      },
      // 运单
      waybillData: {
        orderPieChart: {},
      },
      // 父传子的数据
      timeSearch: {},
      statistics: true,
      loading: false,
      date: [],
      searchForm: {
        // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        startDate: "",
        endDate: "",
      },
      totalStatistics: [], //总统计
      form: {},
      columns: [
        {
          title: "",
          key: "mobile",
          minWidth: 230,
        },
        {
          title: "承运单",
          key: "carry_num",
          minWidth: 230,
          render: (h, params) => {
            if (params.index == 0) {
              if (params.row.carry_num != "" && params.row.carry_num != null) {
                return h("div", params.row.carry_num + " 单");
              } else {
                return h("div", 0 + " 单");
              }
            } else {
              if (params.row.carry_num != "" && params.row.carry_num != null) {
                return h("div", params.row.carry_num + " %");
              } else {
                return h("div", 0 + " %");
              }
            }
          },
        },
        {
          title: "总运量",
          key: "carry_weight",
          minWidth: 230,
          render: (h, params) => {
            if (params.index == 0) {
              if (
                params.row.carry_weight != "" &&
                params.row.carry_weight != null
              ) {
                return h("div", params.row.carry_weight + " 吨");
              } else {
                return h("div", 0 + " 吨");
              }
            } else {
              if (
                params.row.carry_weight != "" &&
                params.row.carry_weight != null
              ) {
                return h("div", params.row.carry_weight + " %");
              } else {
                return h("div", 0 + " %");
              }
            }
          },
        },
        {
          title: "总收入",
          key: "carry_price",
          minWidth: 230,
          render: (h, params) => {
            if (params.index == 0) {
              if (
                params.row.carry_price != "" &&
                params.row.carry_price != null
              ) {
                return h("div", params.row.carry_price + " 元");
              } else {
                return h("div", 0 + " 元");
              }
            } else {
              if (
                params.row.carry_price != "" &&
                params.row.carry_price != null
              ) {
                return h("div", params.row.carry_price + " %");
              } else {
                return h("div", 0 + " %");
              }
            }
          },
        },
        {
          title: "委托单",
          key: "match_num",
          minWidth: 230,
          render: (h, params) => {
            if (params.index == 0) {
              if (params.row.match_num != "" && params.row.match_num != null) {
                return h("div", params.row.match_num + " 单");
              } else {
                return h("div", 0 + " 单");
              }
            } else {
              if (params.row.match_num != "" && params.row.match_num != null) {
                return h("div", params.row.match_num + " %");
              } else {
                return h("div", 0 + " %");
              }
            }
          },
        },
        {
          title: "总运量",
          key: "match_weight",
          minWidth: 230,
          render: (h, params) => {
            if (params.index == 0) {
              if (
                params.row.match_weight != "" &&
                params.row.match_weight != null
              ) {
                return h("div", params.row.match_weight + " 吨");
              } else {
                return h("div", 0 + " 吨");
              }
            } else {
              if (
                params.row.match_weight != "" &&
                params.row.match_weight != null
              ) {
                return h("div", params.row.match_weight + " %");
              } else {
                return h("div", 0 + " %");
              }
            }
          },
        },
        {
          title: "总支出",
          key: "match_price",
          minWidth: 220,
          render: (h, params) => {
            if (params.index == 0) {
              if (
                params.row.match_price != "" &&
                params.row.match_price != null
              ) {
                return h("div", params.row.match_price + " 元");
              } else {
                return h("div", 0 + " 元");
              }
            } else {
              if (
                params.row.match_price != "" &&
                params.row.match_price != null
              ) {
                return h("div", params.row.match_price + " %");
              } else {
                return h("div", 0 + " %");
              }
            }
          },
        },
      ],
      data: [], // 表单数据
      pageNumber: 1, // 当前页数
      pageSize: 10, // 页面大小
      total: 0, // 表单数据总数
      carryTotal: 0,
      entrustTotal: 0,
      waybillTotal: 0,
      goodWeight: 0,
      realGoodWeight: 0,
      transGoodWeight: 0,
      imgUrl: "",
      exportRemarks: "",
    };
  },
  methods: {
    init() {
      this.getDataList();
    },
    handleSearch() {
      // 环比统计区间
      let ringRatioStart1 = this.getPreMonth(this.searchForm.startDate);
      let ringRatioEnd1 = this.getPreMonth(this.searchForm.endDate);
      // 自然日
      this.ringRatioDay = this.getRemainderTime(ringRatioStart1, ringRatioEnd1);
      // 开始
      this.ringRatioStart = this.dateFormat(ringRatioStart1);
      // 结束
      this.ringRatioEnd = this.dateFormat(ringRatioEnd1);

      // 同比统计区间
      let yearStartNew = this.yearStatistics(this.searchForm.startDate);
      let yearStartEnd = this.yearStatistics(this.searchForm.endDate);

      // 自然日
      this.yearDay = this.getRemainderTime(yearStartNew, yearStartEnd);
      // 开始
      this.yearStart = this.dateFormat(yearStartNew);
      // 结束
      this.yearEnd = this.dateFormat(yearStartEnd);
      this.getDataList();
    },
    // 获取卸货省份数
    handleReset() {
      // 上传记录
      let param = new FormData(); // 创建form对象
      // param.append("file", a); // 通过append向form对象添加数据
      param.append("fileName", "运营分析报告"); // 添加form表单中其他数据
      param.append("fileType", 7); // 通过append向form对象添加数据
      param.append("remarks", this.exportRemarks); // 添加form表单中其他数据
      addDownloadRecord(param).then((res) => {
        if (res.code == 200) {
          this.loadingPDF = true;
          html2canvas(this.$refs.qrCodeDiv).then((canvas) => {
            const link = document.createElement("a");
            link.href = canvas.toDataURL();
            link.setAttribute(
              "download",
              res.result + " " + "运营分析报告" + ".png"
            );
            link.style.display = "none";
            document.body.appendChild(link);
            link.click();
            this.loadingPDF = false;
          });
        } else {
          return this.$Message.error(res.message);
        }
      });
    },
    changeDate(val) {
      //改变选择日期 不能大于三十天
      this.searchForm.startDate = val[0];
      this.searchForm.endDate = val[1];
      let startTme = val;
      let start1 = startTme[0].split("-");
      let start2 = startTme[1].split("-");
      this.startime = start1[0] + "年" + start1[1] + "月" + start1[2] + "日";
      this.endtime = start2[0] + "年" + start2[1] + "月" + start2[2] + "日";
      let first = this.searchForm.startDate; //开始时间
      let second = this.searchForm.endDate; //结束时间
      var data1 = Date.parse(first.replace(/-/g, "/"));
      var data2 = Date.parse(second.replace(/-/g, "/"));
      var datadiff = data2 - data1;
      var time = 31 * 24 * 60 * 60 * 1000;
      if (first.length > 0 && second.length > 0) {
        if (datadiff < 0 || datadiff > time) {
          this.$Message.warning("前后时间间隔不能大于31天");
          this.beyondTiem = true;
          return false;
        }
      } else {
        this.beyondTiem = false;
      }
    },
    yearStatistics(date) {
      var arr = date.split("-");
      var year = arr[0] - 1; //获取当前日期的年份
      var month = arr[1]; //获取当前日期的月份
      var day = arr[2]; //获取当前日期的日
      return year + "-" + month + "-" + day;
    },
    // 格式化时间
    dateFormat(date) {
      let start1 = date.split("-");
      return start1[0] + "年" + start1[1] + "月" + start1[2] + "日";
    },
    // 获取前一个月的时间
    getPreMonth(date) {
      var arr = date.split("-");
      var year = arr[0]; //获取当前日期的年份
      var month = arr[1]; //获取当前日期的月份
      var day = arr[2]; //获取当前日期的日
      var days = new Date(year, month, 0);
      days = days.getDate(); //获取当前日期中月的天数
      var year2 = year;
      var month2 = parseInt(month) - 1;
      if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
      }
      var day2 = day;
      var days2 = new Date(year2, month2, 0);
      days2 = days2.getDate();
      if (day2 > days2) {
        day2 = days2;
      }
      if (month2 < 10) {
        month2 = "0" + month2;
      }
      var t2 = year2 + "-" + month2 + "-" + day2;
      return t2;
    },

    // 自然日
    getRemainderTime(dateString1, dateString2) {
      var startDate = Date.parse(dateString1);
      var endDate = Date.parse(dateString2);
      var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      return Math.round(days);
    },
    getDataList() {
      this.timeSearch = this.searchForm;
      this.statistics = false;
      this.$nextTick(() => {
        this.statistics = true;
      });
      this.loading = true;
      // 平台端 --- 运营报告-本期、同比、环比
      let arr = [];
      let datas = {};
      operateRingRatio(this.searchForm).then((res) => {
        datas = res.result;
        arr.push(datas.currentPeriod);
        arr.push(datas.ringRatio);
        arr.push(datas.yearOnYear);
        if (arr.length > 0) {
          this.data = arr;
          this.data[0].mobile = "本期";
          this.data[1].mobile = "同比";
          this.data[2].mobile = "环比";
        }
        this.loading = false;
      });
    },
    // 货源
    childSourceGoods(val) {
      this.goodsData = val;
    },
    // 订单
    childOrder(val) {
      this.orderData = val;
      this.carryTotal = 0;
      this.orderData.entrustedBrokenLine.forEach((item) => {
        if (item.carry_money != "0") {
          this.carryTotal += item.carry_money;
        }
        if (item.entrust_money != "0") {
          this.entrustTotal += item.entrust_money;
        }
      });
    },
    // 运单
    childTransport(val) {
      this.waybillTotal = 0;
      this.waybillData = val;
      for (var i in this.waybillData.orderPieChart) {
        this.waybillTotal += this.waybillData.orderPieChart[i];
      }
      this.waybillData.orderBrokenLine.forEach((item) => {
        if (item.good_weight != "0") {
          this.goodWeight += item.good_weight;
        }
        if (item.real_good_weight != "0") {
          this.realGoodWeight += item.real_good_weight;
        }
        if (item.trans_good_weight != "0") {
          this.transGoodWeight += item.trans_good_weight;
        }
      });
    },
  },
  created() {
    var myDate = new Date();
    var y = myDate.getFullYear(); //年
    var m = myDate.getMonth() + 1; //获取月份
    var d = myDate.getDate(); //获取日期
    var s = myDate.getHours();
    var f = myDate.getMinutes();
    var mm = myDate.getSeconds();
    this.endtime = y + "年" + m + "月" + d + "日";
    this.currentTime = y + "年" + m + "月" + d + "日" + s + ":" + f + ":" + mm;
    var time = myDate.toLocaleDateString().split("/").join("-");
    var sdtime4 = new Date(time).setMonth(new Date(time).getMonth() - 1); //一个月
    var now = new Date(sdtime4);
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //获取月份
    var date = now.getDate(); //获取日期
    let startimes = year + "-" + month + "-" + date;
    this.startime = year + "年" + month + "月" + date + "日";
    this.searchForm.startDate = startimes;
    this.searchForm.endDate = time;
    this.date.push(this.searchForm.startDate);
    this.date.push(this.searchForm.endDate);
  },
  mounted() {
    this.init();
    this.$nextTick(() => {
      // 环比统计区间
      let ringRatioStart1 = this.getPreMonth(this.searchForm.startDate);
      let ringRatioEnd1 = this.getPreMonth(this.searchForm.endDate);
      // 自然日
      this.ringRatioDay = this.getRemainderTime(ringRatioStart1, ringRatioEnd1);
      // 开始
      this.ringRatioStart = this.dateFormat(ringRatioStart1);
      // 结束
      this.ringRatioEnd = this.dateFormat(ringRatioEnd1);

      // 同比统计区间
      let yearStartNew = this.yearStatistics(this.searchForm.startDate);
      let yearStartEnd = this.yearStatistics(this.searchForm.endDate);
      // 自然日
      this.yearDay = this.getRemainderTime(yearStartNew, yearStartEnd);
      // 开始
      this.yearStart = this.dateFormat(yearStartNew);
      // 结束
      this.yearEnd = this.dateFormat(yearStartEnd);
    });
  },
};
</script>
<style lang="less">
.company {
  margin-left: 10px;
  display: flex;
  .companyimg {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .companyinformation {
    display: inline-block;
    margin-left: 13px;
    margin-top: 10px;
  }
}
.Operation_analysis {
  font-size: 16px;
  font-weight: 600;
  margin-left: 98px;
}
.tiems {
  // width: 250px;
  margin-left: 95px;
  margin-top: 24px;
}
.Lines {
  margin-top: 10px;
  border-bottom: 2px solid #545454;
  width: 98.8%;
  margin-left: 10px;
}
.QuantityStatistics,
.Goods,
.Ordercs {
  margin-top: -5px;
  width: 99%;
  margin-left: 10px;
  // padding-bottom: 10px;
}
.QuantityStatistics {
  margin-top: 10px;
  margin-bottom: 30px;
}
.timel {
  margin-left: 35px;
  .el-timeline-item__node--normal {
    width: 50px;
    height: 50px;
    margin-left: -20px;
  }
  .el-timeline-item {
    padding-bottom: 0;
  }
}
.timelineFont {
  position: relative;
  top: 19px;
  left: -39px;
  color: #fff;
}
// .search {
//   height: 100% !important;
// }

.table table {
  // table-layout: auto;
  width: 100% !important;
}
</style>